package com.cainli.gcmdemo;

import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Message.Builder;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

public class ServerActivity extends Activity {
	private static final String TAG = ServerActivity.class.getSimpleName();
	public static String MServerURL = "https://android.googleapis.com/gcm/send";
	private static String  registrationId;
	private static long spaceTime = 0;//毫秒
	private static long sendCount = 0;
	private boolean autoSend = false;
	private EditText msgText,timeSpaceText,numText;
	private CheckBox checkbox;
	private TextView resultTextView;
	private Button sendBtn;
	public static boolean sendFinish = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.server_layout);
		msgText = (EditText) findViewById(R.id.text);
		timeSpaceText = (EditText) findViewById(R.id.send_space);
		numText = (EditText) findViewById(R.id.send_num);
		resultTextView = (TextView) findViewById(R.id.result);
		checkbox = (CheckBox) findViewById(R.id.checkbox);
		checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				autoSend = isChecked;
				timeSpaceText.setEnabled(autoSend);
				numText.setEnabled(autoSend);
			}
		});
		sendBtn = (Button) findViewById(R.id.send);
		sendBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					String msg = msgText.getText().toString();
					msg = msg==null?"":msg;
					if(msg!=null){
						if(autoSend){
							sendMoreMessage(msg);
						}else{
							sendMessage(msg);
						}
					}
				} catch (IOException e) {
					Log.e(TAG,e.getMessage());
				}
			}

		});
		
		final SharedPreferences prefs = this.getSharedPreferences(Constants.GCM_PREFERENCE,Context.MODE_PRIVATE);
        registrationId = prefs.getString(Constants.GCM_REGISTRATION, null);
        if(registrationId == null||registrationId.equals("")){
        	Toast.makeText(ServerActivity.this, "设备注册失败", Toast.LENGTH_SHORT).show();
        	finish();
        }
	}
	
	
	private void initSendCount() {
		String countString = numText.getText().toString();
		countString =countString==null?"0":countString;
		try {
			sendCount = Long.valueOf(countString);
		} catch (Exception e) {
			Toast.makeText(ServerActivity.this, "请输入数字！", Toast.LENGTH_SHORT).show();
			sendCount = 0;
			return;
		}
	}

	private void initSpaceTime() {
		String timeString = timeSpaceText.getText().toString();
		timeString =timeString==null?"0":timeString;
		try {
			spaceTime = Long.valueOf(timeString);
		} catch (Exception e) {
			spaceTime = 0;
			return;
		}
	}
	Sender sender = new Sender("AIzaSyC1YUOTPLxt74ivlxFmptRDCobFO0Kt4L4");
	Builder builder = new Message.Builder();
	public void sendMoreMessage(final String str) throws IOException{
		sendFinish = false;
		sendBtn.setEnabled(false);
		initSpaceTime();
		initSendCount();
		new AsyncTask<Void, String, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				long count = 0;
				long time1,time2;
				while(count < sendCount){
					count++;
					builder.addData("id", "" + count);
					builder.addData("time", "" + Calendar.getInstance().getTime().getTime());
					builder.addData("msg", "");
					time1 = Calendar.getInstance().getTime().getTime();
					Result result;
					try {
						result = sender.send(builder.build(),
								registrationId, 3);
						Log.v(TAG, result.toString());
						this.publishProgress(""+count+":"+result.toString());
					} catch (IOException e) {
						Log.e(TAG, e.getMessage());
					}
					time2 = Calendar.getInstance().getTime().getTime()-time1;
					if(time2<spaceTime){
						try {
							Thread.currentThread().sleep(spaceTime-time2);
						} catch (InterruptedException e) {
							Log.e(TAG,e.getMessage());
						}
					}
				}
				return null;
			}
			@Override
			protected void onProgressUpdate(String... values) {
				super.onProgressUpdate(values);
				resultTextView.setText(values[0]);
			}
			@Override
			protected void onPostExecute(Void result) {
				sendBtn.setEnabled(true);
				sendFinish = true;
			};
		}.execute();

	}

//	Thread  thread = new Thread(new Runnable() {
//	@Override
//	public void run() {
//		 send();
//		runOnUiThread(new Runnable() {
//			public void run() {
//				sendBtn.setEnabled(true);
//				sendFinish = true;
//			}
//		});
//	}
//
//});
//thread.setPriority(Thread.MAX_PRIORITY);
//thread.start();
//	long lastTime = 0L;
//	long nowTime = 0L;
//	private void send() {
//		long count = 0;
//		while(count < sendCount){
//			while (true) {
//				nowTime = SystemClock.uptimeMillis();
//				if (nowTime - lastTime >= spaceTime) {
//					lastTime = nowTime;
//					break;
//				}
//			}
//			count++;
//			builder.addData("id", "" + count);
//			builder.addData("time", "" + lastTime);
//			builder.addData("msg", "");
//			Result result;
//			try {
//				result = sender.send(builder.build(),
//						registrationId, 5);
//				Log.v(TAG, result.toString());
//			} catch (IOException e) {
//				Log.e(TAG, e.getMessage());
//			}
//		}
//	}
	
	public void sendMessage(final String str) throws IOException{
		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				Sender sender = new Sender("AIzaSyC1YUOTPLxt74ivlxFmptRDCobFO0Kt4L4");
				Builder builder = new Message.Builder();
				builder.addData("msg",str);
				Result result;
				try {
					result = sender.send(builder.build(), registrationId, 3);
					Log.v(TAG,result.toString());
				} catch (IOException e) {
					Log.e(TAG,e.getMessage());
				}
				return null;
			}
		}.execute();
	}

}
